Bias detection and mitigation in AutoAI¶

This notebook contains the steps and code to demonstrate support of AutoAI experiments with bias detection/mitigation in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals¶

The learning goals of this notebook are:

  • Work with Watson Machine Learning experiment to train AutoAI models with bias detection and mitigation.
  • Compare trained models quality and fairness.

Contents¶

This notebook contains the following parts:

  1. Setup
  2. Optimizer definition
  3. Bias detection and mitigation
  4. Inspection of pipelines
  5. Cleanup
  6. Summary and next steps

1. Set up the environment¶

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Create a Watson Machine Learning (WML) Service instance (a free plan is offered and information about how to create the instance can be found here).

Connection to WML¶

Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide platform api_key and instance location.

You can use IBM Cloud CLI to retrieve platform API Key and instance location.

API Key can be generated in the following way:

ibmcloud login
ibmcloud iam api-key-create API_KEY_NAME

In result, get the value of api_key from the output.

Location of your WML instance can be retrieved in the following way:

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME

In result, get the value of location from the output.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.

You can also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below.

Action: Enter your api_key and location in the following cell.

In [1]:
api_key = 'PASTE YOUR PLATFORM API KEY HERE'
location = 'PASTE YOUR INSTANCE LOCATION HERE'
In [2]:
wml_credentials = {
    "apikey": api_key,
    "url": 'https://' + location + '.ml.cloud.ibm.com'
}

Install and import the ibm-watson-machine-learning and dependencies¶

Note: ibm-watson-machine-learning documentation can be found here.

In [ ]:
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install -U autoai-libs | tail -n 1
!pip install scikit-learn==1.0.2 | tail -n 1
!pip install wget | tail -n 1
!pip install -U 'lale[fairness]' | tail -n 1

Working with spaces¶

First of all, you need to create a space that will be used for your work with AutoAI. If you do not have space already created, you can use Deployment Spaces Dashboard to create one.

  • Click New Deployment Space
  • Create an empty space
  • Select Cloud Object Storage
  • Select Watson Machine Learning instance and press Create
  • Copy space_id and paste it below

Action: assign space ID below

In [4]:
space_id = 'PASTE YOUR SPACE ID HERE'

You can use list method to print all existing spaces.

client.spaces.list(limit=10)
In [5]:
from ibm_watson_machine_learning import APIClient

client = APIClient(wml_credentials)
client.set.default_space(space_id)
Out[5]:
'SUCCESS'

Optimizer definition¶

Training data connection¶

Define connection information to COS bucket and training data CSV file. This example uses the German Credit Risk dataset.

The dataset can be downloaded from here.

Action: Upload training data to COS bucket and enter location information below.

In [6]:
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']

filename = 'german_credit_data_biased_training.csv'
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']

Download training data from git repository.

In [7]:
import wget
import os

url = "https://github.com/IBM/watson-machine-learning-samples/raw/master/cloud/data/bias/german_credit_data_biased_training.csv"
if not os.path.isfile(filename): 
    wget.download(url)

Create connection¶

In [8]:
conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucketname,
        'access_key': cos_credentials['credentials']['editor']['access_key_id'],
        'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': cos_credentials['endpoint_url']
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections...
SUCCESS

Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:

conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucket_name,
        'api_key': cos_credentials['apikey'],
        'resource_instance_id': cos_credentials['resource_instance_id'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)

Upload training data¶

In [9]:
from ibm_watson_machine_learning.helpers import DataConnection, S3Location

connection_id = client.connections.get_uid(conn_details)

credit_risk_conn = DataConnection(
    connection_asset_id=connection_id,
    location=S3Location(bucket=bucketname,
                        path=filename))

credit_risk_conn.set_client(client)
training_data_reference=[credit_risk_conn]
credit_risk_conn.write(data=filename, remote_name=filename)

Bias detection and mitigation¶

Terms and definitions:¶

Fairness Attribute - Bias or fairness is typically measured using some fairness attribute such as Gender, Ethnicity, Age, etc.

Monitored/Reference Group - Monitored group are those values of fairness attribute for which we want to measure bias. The rest of the values of the fairness attributes are called as reference group. In case of Fairness Attribute=Gender, if we are trying to measure bias against females, then Monitored group is “Female” and Reference group is “Male”.

Favourable/Unfavourable outcome - An important concept in bias detection is that of favourable and unfavourable outcome of the model. E.g., Claim approved can be considered as a favourable outcome and Claim denied can be considered as an unfavourable outcome.

Disparate Impact - metric used to measure bias (computed as the ratio of percentage of favourable outcome for the monitored group to the percentage of favourable outcome for the reference group). Bias is said to exist if the disparate impact value is below some threshold.

Optimizer configuration¶

Provide input information for AutoAI optimizer:

  • name - experiment name
  • prediction_type - type of the problem
  • prediction_column - target column name
  • fairness_info - bias detection configuration
  • scoring - accuracy_and_disparate_impact combined optimization metric for both accuracy and fairness. For regression learning problem the r2_and_disparate_impact metric is supported (combines r2 and fairness).

fairness_info definition:¶

  • protected_attributes (list of dicts) – subset of features for which fairness calculation is desired.

    • feature - name of feature for which reference_group and monitored_group are specified.
    • reference_group and monitored_group - monitored group are those values of fairness attribute for which we want to measure bias. The rest of the values of the fairness attribute are reference group.
  • favorable_labels and unfavorable_labels – label values which are considered favorable (i.e. “positive”). unfavorable_labels are required when prediction type is regression.

Examples of supported configuration:

fairness_info = {
            "protected_attributes": [
                {"feature": "Age", "reference_group": [[26, 26], [30, 75]], 
                                    "monitored_group": [[18, 25], [27, 29]]}
            ],
            "favorable_labels": ["No Risk"]
            }
fairness_info = {
            "protected_attributes": [
                {"feature": "sex", "reference_group": ['male', 'not specified'], 
                                   "monitored_group": ['female']},
                {"feature": "age", "reference_group": [[26, 100]], "monitored_group": [[18, 25], [27, 29]]}
            ],
            "favorable_labels": [[5000.01, 9000]],
            "unfavorable_labels": [[0, 5000], [9000, 1000000]]
            }
In [10]:
fairness_info = {
            "protected_attributes": [
                {"feature": "Sex", "reference_group": ['male'], "monitored_group": ['female']},
                {"feature": "Age", "reference_group": [[26, 75]], "monitored_group": [[18, 25]]}
            ],
            "favorable_labels": ["No Risk"],
            "unfavorable_labels": ["Risk"],
}
In [11]:
from ibm_watson_machine_learning.experiment import AutoAI


experiment = AutoAI(wml_credentials, space_id=space_id)

pipeline_optimizer = experiment.optimizer(
    name='Credit Risk Prediction and bias detection - AutoAI',
    prediction_type=AutoAI.PredictionType.BINARY,
    prediction_column='Risk',
    scoring='accuracy_and_disparate_impact',
    fairness_info=fairness_info,
    max_number_of_estimators = 1,
    retrain_on_holdout=False
   )

Experiment run¶

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

In [12]:
run_details = pipeline_optimizer.fit(
            training_data_reference=training_data_reference,
            background_mode=False)
Training job 4f4f9870-246a-4d4d-ab05-e1eddd40af00 completed: 100%|████████| [05:31<00:00,  3.31s/it]

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

Get selected pipeline model¶

Download and reconstruct a scikit-learn pipeline model object from the AutoAI training job.

In [13]:
experiment_summary = pipeline_optimizer.summary()
experiment_summary.head()
Out[13]:
Enhancements Estimator training_disparate_impact_Sex training_disparate_impact holdout_accuracy_and_disparate_impact training_roc_auc holdout_disparate_impact_Sex training_average_precision training_accuracy_and_disparate_impact_(optimized) training_log_loss ... holdout_balanced_accuracy training_recall holdout_log_loss training_accuracy holdout_disparate_impact holdout_roc_auc training_balanced_accuracy holdout_disparate_impact_Age training_f1 training_disparate_impact_Age
Pipeline Name
Pipeline_3 HPO, FE SnapDecisionTreeClassifier 1.118238 2.081132 0.148464 0.683937 1.171647 0.476717 0.258060 9.763075 ... 0.702925 0.582514 9.413493 0.717333 1.653118 0.641539 0.683937 1.533538 0.580104 2.036895
Pipeline_4 HPO, FE SnapDecisionTreeClassifier 1.118238 2.081132 0.148464 0.683937 1.171647 0.476717 0.258060 9.763075 ... 0.702925 0.582514 9.413493 0.717333 1.653118 0.641539 0.683937 1.533538 0.580104 2.036895
Pipeline_1 SnapDecisionTreeClassifier 1.163020 1.946575 0.198434 0.691364 1.045489 0.484200 0.130193 9.601894 ... 0.678937 0.598363 10.105659 0.722000 1.526765 0.684961 0.691364 1.472074 0.590830 2.038237
Pipeline_2 HPO SnapDecisionTreeClassifier 1.163020 1.946575 0.198434 0.691364 1.045489 0.484200 0.130193 9.601894 ... 0.678937 0.598363 10.105659 0.722000 1.526765 0.684961 0.691364 1.472074 0.590830 2.038237

4 rows × 22 columns

Visualize pipeline¶

In [14]:
pipeline_name = experiment_summary.index[experiment_summary.holdout_disparate_impact.argmax()]
best_pipeline = pipeline_optimizer.get_pipeline(pipeline_name=pipeline_name)
best_pipeline.visualize()
cluster:(root) numpy_column_selector_0 Numpy- Column- Selector compress_strings Compress- Strings numpy_column_selector_0->compress_strings numpy_replace_missing_values_0 Numpy- Replace- Missing- Values compress_strings->numpy_replace_missing_values_0 numpy_replace_unknown_values Numpy- Replace- Unknown- Values numpy_replace_missing_values_0->numpy_replace_unknown_values boolean2float boolean2float numpy_replace_unknown_values->boolean2float cat_imputer Cat- Imputer boolean2float->cat_imputer cat_encoder Cat- Encoder cat_imputer->cat_encoder float32_transform_0 float32_- transform cat_encoder->float32_transform_0 concat_features Concat- Features float32_transform_0->concat_features numpy_column_selector_1 Numpy- Column- Selector float_str2_float Float- Str2- Float numpy_column_selector_1->float_str2_float numpy_replace_missing_values_1 Numpy- Replace- Missing- Values float_str2_float->numpy_replace_missing_values_1 num_imputer Num- Imputer numpy_replace_missing_values_1->num_imputer opt_standard_scaler Opt- Standard- Scaler num_imputer->opt_standard_scaler float32_transform_1 float32_- transform opt_standard_scaler->float32_transform_1 float32_transform_1->concat_features numpy_permute_array Numpy- Permute- Array concat_features->numpy_permute_array t_gen T- Gen numpy_permute_array->t_gen fs1_0 FS1 t_gen->fs1_0 tam TAM fs1_0->tam fs1_1 FS1 tam->fs1_1 snap_decision_tree_classifier Snap- Decision- Tree- Classifier fs1_1->snap_decision_tree_classifier

Each node in the visualization is a machine-learning operator (transformer or estimator). Each edge indicates data flow (transformed output from one operator becomes input to the next). The input to the root nodes is the initial dataset and the output from the sink node is the final prediction. When you hover the mouse pointer over a node, a tooltip shows you the configuration arguments of the corresponding operator (tuned hyperparameters). When you click on the hyperlink of a node, it brings you to a documentation page for the operator.

Test pipeline model locally¶

Read the data¶

In [18]:
X_train, X_holdout, y_train, y_holdout = pipeline_optimizer.get_data_connections()[0].read(with_holdout_split=True)

Calculate metrics¶

For detail description of used metrics you can check the documentation:

  • accuracy
  • disparate_impact

  • accuracy and disparate impact

In [16]:
from lale.lib.aif360 import disparate_impact, accuracy_and_disparate_impact
from sklearn.metrics import accuracy_score

predicted_y = best_pipeline.predict(X_holdout.values)
disparate_impact_scorer = disparate_impact(**fairness_info)
accuracy_disparate_impact_scorer = accuracy_and_disparate_impact(**fairness_info)

print("Accuracy: {:.2f}".format(accuracy_score(y_true= y_holdout, y_pred=predicted_y)))
print("Disparate impact: {:.2f}".format(disparate_impact_scorer(best_pipeline, X_holdout, y_holdout)))
print("Accuracy and disparate impact: {:.2f}".format(accuracy_disparate_impact_scorer(best_pipeline, X_holdout, y_holdout)))
Accuracy: 0.73
Disparate impact: 1.65
Accuracy and disparate impact: 0.15

Fairness insights¶

You can analize favorable outcome distributions using visualize method from utils module.

In [17]:
from ibm_watson_machine_learning.utils.autoai.fairness import visualize

visualize(run_details, pipeline_name)

Clean up¶

If you want to clean up all created assets:

  • experiments
  • trainings
  • pipelines
  • model definitions
  • models
  • functions
  • deployments

please follow up this sample notebook.

Summary and next steps¶

You successfully completed this notebook!

As a next step you can deploy and score the model: Sample notebook.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors¶

Lukasz Cmielowski, PhD, is an Automation Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Dorota Lączak, software engineer in Watson Machine Learning at IBM

Szymon Kucharczyk, software engineer in Watson Machine Learning at IBM

Copyright © 2021 IBM. This notebook and its source code are released under the terms of the MIT License.